import functools
from dataclasses import dataclass
from typing import List

import pywebio
import pywebio_battery
from pywebio import output, pin,input

from emi.bar.data import CategoryMeta, CategorySymbolMeta
from emi.bar.storage import MarketMetaStorage
from emi.bar.db import MarketMeta
from emi.core.DBSource import DBSource
from emiui.pywebio.widget import DataLoaderView


class MarketMetaUI:

    def __init__(self,market_meta:MarketMeta):
        self.market_meta = market_meta

    async def show(self):
        market_meta = self.market_meta
        output.put_text(f"分类数量:{market_meta.category_count()}， 个股数量:{market_meta.symbol_count()}")
        output.put_markdown("----")

        """
         {
                    "label":(str) option label,
                    "value":(object) option value,
                    "selected":(bool, optional) whether the option is initially selected,
                    "disabled":(bool, optional) whether the option is initially disabled
                }
        """
        options = []
        options.append({
            "label": "按分类",
            "value": 3,
        })

        options.append({
            "label": "按个股",
            "value": 2,
        })

        output.put_tabs([
            {'title': '按分类', 'content': [
                output.put_scope("category")

            ]},
            {'title': '按个股', 'content': [output.put_text("sdf")]},
            ##{'title': '备份管理', 'content': [output.put_scope("backup")]},

        ])
        await self.show_category()
        await self.on_category_type_select_changed(None)





    async def show_category(self,):

        with output.use_scope("category",clear=True):
            type_name_map = self.market_meta.get_category_type_name_map()

            category_type_option = [
                {"label": "全部",
                  "value": None,
                 "selected": True}
            ]

            for _type,_name in type_name_map.items():
                category_type_option.append({
                    "label": _name,
                    "value": _type,
                })

            pin.put_radio("category_type", category_type_option, inline=True, label="type")

            # output.put_row([
            #     pin.put_select("category_code", {}, label="code:").style("height:40px"),
            # ])

            output.put_markdown("---")
            output.put_scope("category_symbol")
        pin.pin_on_change("category_type",onchange=self.on_category_type_select_changed)

    async def on_category_type_select_changed(self,data):
        c_type = await pin.pin['category_type']
        meta = self.market_meta
        category_metas = meta.get_all_category_metas(type=c_type)   ### 行业分类。

        @dataclass
        class CategoryItem:

            meta:CategoryMeta
            members:List[CategorySymbolMeta]


        class _CategoryListView(DataLoaderView[CategoryMeta, CategoryItem]):

            def load_item_data(self, items: List[CategoryMeta]) -> List[CategoryItem]:
                """
                加载item信息的详情数据 (在后台线程执行）
                :param items:
                :return:
                """
                _items = []
                for c_meta in items:
                    _members = meta.get_category_symbol_metas(c_meta.code)
                    _items.append(CategoryItem(meta=c_meta,members=_members))

                return _items

            def get_item_view(self, offset: int, is_head: bool, data: CategoryItem):
                if is_head:
                    return ["序号","code", "名称", "成员个数",""]
                else:
                    meta = data.meta
                    async def popup_members_info():
                        class _ListView(DataLoaderView[CategorySymbolMeta, CategorySymbolMeta]):

                            def get_item_view(self, offset: int, is_head: bool, data: CategorySymbolMeta):
                                if is_head:
                                    return ["序号", "code", "名称"]
                                else:

                                    return [offset, f"{data.code}", f"{data.name}"],

                        with output.popup(f"{meta.name}({meta.code})的成员股列表"):
                            report_list_view = _ListView("category_meta_lists", data.members, page_size=20)
                            await report_list_view.show()

                    return [offset,f"{data.meta.code}",f"{data.meta.name}",len(data.members),
                            output.put_button("查看",link_style=True,onclick=popup_members_info) ],


        with output.use_scope("category_symbol",clear=True):

            report_list_view = _CategoryListView("__sdflsf", category_metas, page_size=30)
            await report_list_view.show()









if __name__ == '__main__':
    from emi.core.App import App

    context = App()
    db_source = DBSource.of_name(context, "china_market")  ## 中国市场结构数据

    market_meta = MarketMetaStorage(db_source)
    ui = MarketMetaUI(market_meta)
    pywebio.start_server(functools.partial(MarketMetaUI.show, ui),
                         port=8080,
                         debug=True)